<!DOCTYPE HTML>
<head>
    <title>WebSocket交互</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <!-- 页面编码 -->
    <link rel="icon" type="image/x-icon" href="images/favicon.ico"/> <!-- 页面ICON -->
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css"/>
    <script type="text/javascript">     // WebSocket是需要通过JS编写的
    	url = "ws://localhost:8080/websocket/yootk-token";  // 此时采用的是一个默认的token标记
    	window.onload = function() {    // 本次不使用开发框架，直接采用原生的JS进行开发
    		webSocket = new WebSocket(url);     // 获取WebSocket类的实例化对象
    		webSocket.onopen = function(dev) {  // 进行连接的开启
    			document.getElementById("messageDiv").innerHTML += 
    				"<p>服务器连接成功，开始进行消息的交互处理。</p>"
    		}
    		webSocket.onclose = function() {
    			document.getElementById("messageDiv").innerHTML += 
    				"<p>消息交互完毕，关闭连接通道。</p>"	
    		}
    		document.getElementById("send").addEventListener("click", function() {
    			inputMessage = document.getElementById("msg").value;    // 获取文本输入内容
    			webSocket.send(inputMessage);   // 进行消息的发送
    			webSocket.onmessage = function(obj) {   // 消息的回应处理
    				document.getElementById("messageDiv").innerHTML += 
    					"<p>" + obj.data + "</p>";  // 接收内容响应
    				document.getElementById("msg").value = ""; // 清空文本输入框
    			}
    		});
    		document.getElementById("close").addEventListener("click", function() {
    			webSocket.close();  // 关闭
    		})
    	}
    </script>
</head>
<body>
<div>&nbsp;</div>
<div class="row" style="margin: 10px;">
    <div class="panel panel-success">
        <div class="panel-heading">
            <strong><i class="glyphicon glyphicon-th-list"></i>&nbsp;WebSocket数据交互</strong>
        </div>
        <div class="panel-body">
			<div id="inputDiv">
				<form class="form-horizontal" id="messageform">
					<div class="form-group" id="midDiv">
						<label class="col-md-2 control-label">输入信息：</label>
						<div class="col-md-8">
							<input type="text" id="msg" name="msg" class="form-control" placeholder="请输入交互信息...">
						</div>
						<div class="col-md-2">
							<button type="button" class="btn btn-primary btn-sm" id="send">发送</button>
							<button type="button" class="btn btn-danger btn-sm" id="close">关闭</button>
						</div>
					</div>
				</form>
			</div>
			<div id="messageDiv"></div>
        </div>
        <div class="panel-footer">
            <div style="text-align:right;">
                <img src="images/logo.png" style="height: 30px;">
                <strong>沐言科技（www.yootk.com） —— 新时代软件教育领导品牌</strong>
            </div>
        </div>
    </div>
</div>
</body>
</html>
